import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { UserService } from 'src/user/user.service';

@Injectable()
export class AdminGuard implements CanActivate {

  constructor(private userService: UserService, private reflector:Reflector){}
  async canActivate(
    context: ExecutionContext,
  ): Promise<boolean> {
    const req = context.switchToHttp().getRequest();
    console.log('req.user', req.user)
    const user = await this.userService.find(req.user.username)
    console.log(user)
    const rolesReflectors = this.reflector.get<number[]>('roles', context.getHandler())
    console.log({ rolesReflectors })
    if (!rolesReflectors) return true;
    if (user?.roles.find(role => rolesReflectors.includes(role.id))) {
      return true
    }
    return false;
  }
}
